package cn.mujiankeji.mbrowser.数据.数据库

import androidx.room.*
import kotlinx.coroutines.flow.Flow

/**
 * 主页标签数据模型
 */
@Entity
data class DBHomeTab(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Long = 0,
    
    // 标签基本信息
    @ColumnInfo(name = "name")
    var 标签名称: String = "",
    
    @ColumnInfo(name = "icon_path")
    var 图标路径: String = "", // 可以是图标资源路径或URL
    
    @ColumnInfo(name = "link_url")
    var 链接URL: String = "", // 点击标签后跳转的URL
    
    // 标签显示与排序
    @ColumnInfo(name = "sort_order")
    var 排序位置: Int = 0, // 用于排序
    
    @ColumnInfo(name = "group_id")
    var 组ID: Long = 0, // 0表示不属于任何组，其他值表示所属组的ID
    
    @ColumnInfo(name = "is_group")
    var 是否为组: Boolean = false, // 标识是否为一个组文件夹
    
    // 标签样式
    @ColumnInfo(name = "background_color")
    var 背景颜色: Int = 0, // 十六进制颜色值
    
    @ColumnInfo(name = "text_color")
    var 文字颜色: Int = 0, // 十六进制颜色值
    
    // 其他配置
    @ColumnInfo(name = "custom_icon")
    var 自定义图标: Boolean = false, // 是否使用自定义图标而非系统图标
    
    @ColumnInfo(name = "create_time")
    var 创建时间: Long = System.currentTimeMillis(),
    
    @ColumnInfo(name = "update_time")
    var 更新时间: Long = System.currentTimeMillis()
)


/**
 * 主页标签DAO接口
 */
@Dao
interface DaoHomeTab {
    @Query("SELECT * FROM DBHomeTab ORDER BY sort_order ASC")
    fun 获取所有标签(): Flow<List<DBHomeTab>>
    
    @Query("SELECT * FROM DBHomeTab WHERE group_id = :组ID ORDER BY sort_order ASC")
    fun 获取组内标签(组ID: Long): Flow<List<DBHomeTab>>
    
    @Query("SELECT * FROM DBHomeTab WHERE is_group = 1 ORDER BY sort_order ASC")
    fun 获取所有组(): Flow<List<DBHomeTab>>
    
    @Query("SELECT * FROM DBHomeTab WHERE group_id = 0 AND is_group = 0 ORDER BY sort_order ASC")
    fun 获取所有非组标签(): Flow<List<DBHomeTab>>
    
    @Insert
    suspend fun 添加标签(标签: DBHomeTab): Long
    
    @Update
    suspend fun 更新标签(标签: DBHomeTab)
    
    @Delete
    suspend fun 删除(标签: DBHomeTab)
    
    @Query("DELETE FROM DBHomeTab WHERE id = :id")
    suspend fun 删除(id: Long)
    
    @Query("UPDATE DBHomeTab SET sort_order = :排序位置 WHERE id = :id")
    suspend fun 更新标签排序(id: Long, 排序位置: Int)
    
    @Query("UPDATE DBHomeTab SET group_id = :组ID WHERE id = :id")
    suspend fun 移动标签到组(id: Long, 组ID: Long)
    
    @Query("SELECT COUNT(*) FROM DBHomeTab")
    suspend fun 获取标签数量(): Int

    // 取最大的排序
    @Query("SELECT MAX(sort_order) FROM DBHomeTab")
    suspend fun 获取最大排序(): Int?


    
    @Transaction
    suspend fun 批量更新排序(标签列表: List<Pair<Long, Int>>) {
        标签列表.forEach { (id, 排序) ->
            更新标签排序(id, 排序)
        }
    }
} 